<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="小区" prop="villageId">
        <el-select  v-model="queryParams.villageId" placeholder="请选择小区">
                <el-option
                        v-for="item in villageList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                </el-option>
              </el-select>
      </el-form-item>
      <el-form-item label="楼栋" prop="buildNum">
        <el-input
          v-model="queryParams.buildNum"
          placeholder="请输入楼栋"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单元" prop="unit">
        <el-input
          v-model="queryParams.unit"
          placeholder="请输入单元"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:buildFloor:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:buildFloor:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:buildFloor:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:build:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="buildList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <!-- <el-table-column label="小区ID" align="center" prop="villageId" /> -->
      <el-table-column label="小区名称" align="center" prop="villageName" />
      <el-table-column label="楼栋" align="center" prop="buildNum" />
      <el-table-column label="单元" align="center" prop="unit" />
      <el-table-column label="楼栋识别码" align="center" prop="identify" />
      <!-- <el-table-column label="楼层" align="center" prop="floor" /> -->
      <el-table-column label="备注信息" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:buildFloor:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:buildFloor:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改楼栋管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="小区" prop="villageId">
                      <el-select v-if="user.name == 'admin'" v-model="form.villageId"
                                  placeholder="请选择小区">
                          <el-option
                                  v-for="item in villageList"
                                  :key="item.id"
                                  :label="item.name"
                                  :value="item.id">
                          </el-option>
                      </el-select>
                      <el-select v-else disabled v-model="form.villageId">
                          <el-option
                                  v-for="item in villageList"
                                  :key="item.id"
                                  :label="item.name"
                                  :value="item.id">
                          </el-option>
                      </el-select>
                  </el-form-item>
        <el-form-item label="楼栋" prop="buildNum">
          <el-input v-model="form.buildNum" placeholder="请输入楼栋" />
        </el-form-item>
        <el-form-item label="单元" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单元" />
        </el-form-item>
        <el-form-item label="楼栋识别码" prop="identify">
          <el-input v-model="form.identify" placeholder="请输入识别码" />
        </el-form-item>
        <el-form-item label="楼层">
            <el-checkbox-group v-model="form.floor">
              <el-checkbox v-for="dict in floorOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue">
                  {{dict.dictLabel}}
              </el-checkbox>
            </el-checkbox-group>
        </el-form-item>

        
        <el-form-item label="备注信息" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBuild, getBuild, delBuild, addBuild, updateBuild, exportBuild } from "@/api/system/buildFloor";
import { listVillage } from "@/api/youma/village";

export default {
  name: "Build",
  components: {
  },
  data() {
    return {
      // 物业唯一的小区id
      propertyVillId: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 楼栋管理表格数据
      buildList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 楼层字典
      floorOptions: [],
      villageList:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        villageId: null,
        buildNum: null,
        unit: null,
        floor: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        villageId: [
          { required: true, message: "小区ID不能为空", trigger: "blur" }
        ],
        buildNum: [
          { required: true, message: "楼栋不能为空", trigger: "blur" }
        ],
        unit: [
          { required: true, message: "单元不能为空", trigger: "blur" }
        ],
        floor: [
          { required: true, message: "楼层不能为空", trigger: "blur" }
        ],
      },
      user:{},
    };
  },
  async created() {
    this.user = this.$store.state.user;
    // 获取登录用户的小区id
    await this.getVillage();
    this.getDicts("floor").then(response => {
      this.floorOptions = response.data;
    });
    this.getList();
    // this.getVillageList();
    
  },
  methods: {
    /** 查询社区列表 */
    async getVillage() {
      this.loading = true;
      await listVillage({ pageNum: 1, pageSize: 1000 }).then((response) => {
        console.log("登录者身份", this.user);
        if (this.user.roles.includes("property")) {
          // 如果是物业身份 过滤出所属小区 获取小区id
          this.villageList = response.rows.filter(
            (e) => e.uid === this.user.name
          );
          console.log('物业小区列表', this.villageList)
          if (this.villageList) {
            // 获取小区id
            this.queryParams.villageId = this.villageList[0]?.id;
            this.form.villageId = this.villageList[0]?.id;
            this.propertyVillId = this.villageList[0]?.id
            console.log('小区id', this.form.villageId);
          }
        } else {
          // 如果身份为超级管理员  获取所有小区列表
          this.villageList = response.rows;
        }
        this.loading = false;
      });
    },
    /** 查询楼栋管理列表 */
    getList() {
      this.loading = true;
      const params = {
        ...this.queryParams,
        // villageName: this.user?.name
      }
      // params => this.queryParams
      listBuild(params).then(response => {
        this.buildList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        villageId: null,
        buildNum: null,
        unit: null,
        floor: null,
        identify: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // 如果身份为物业则只能添加本小区内的楼栋 默认绑定本小区id
      this.form.villageId = this.propertyVillId ? this.propertyVillId : null
      this.open = true;
      this.title = "添加楼栋管理";
      // fix
      this.form.floor = []
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      // fix bug
      this.form.floor = []
      // end
      const id = row.id || this.ids
      getBuild(id).then(response => {
        this.form = response.data;
        // fix bug
        // 字符串转数组
        this.form.floor = this.form.floor.split(',')
        console.log('楼层form.floor', this.form.floor)
        this.open = true;
        this.title = "修改楼栋管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            // floor字段 数组转字符串
            const params = {
              ...this.form,
              floor: this.form?.floor.join()
            }
            updateBuild(params).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // floor字段 数组转字符串
            const params = {
              ...this.form,
              floor: this.form?.floor.join()
            }
            addBuild(params).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除楼栋管理编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delBuild(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有楼栋管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportBuild(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
    /** 查询社区列表 */
    // async getVillageList() {
    //   await listVillage({pageNum: 1, pageSize: 1000}).then(response => {
    //     // if (this.user.roles.includes("property")) {
    //     //   this.villageList = response.rows.filter(e => e.uid === this.user.name);
    //     //   if (this.villageList) {
    //     //     this.form.villageId = this.villageList[0].id;
    //     //     this.queryParams.villageId = this.villageList[0].id;
    //     //     this.changeVillage(this.villageList[0].id);
    //     //   }
    //     // } else {
    //       this.villageList = response.rows;
    //     // }
    //     // this.total = this.villageList.length;
    //     // this.loading = false;
    //   });
    // },
  }
};
</script>
